package cn.icanci.pool;

import cn.icanci.pool.exceptions.ResourceNotFoundException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Author: icanci
 * @ProjectName: kangaroo-orm
 * @PackageName: cn.icanci.pool
 * @Date: Created in 2020/9/1 16:15
 * @ClassAction: 袋鼠数据库连接池
 * -
 * - KangarooDatabaseConnectionPool
 */
public class KangarooPool {
    /*---------------------------- 单例创建对象 ---------------------------- */

    /**
     * 因为数据库连接池池是重量级对象
     * 饿汉式单例模式模式
     */
    private static final KangarooPool INSTANCE = new KangarooPool();

    private KangarooPool() {
    }

    /**
     * 返回一个连接池对象
     *
     * @return 返回KangarooPool对象
     */
    public static KangarooPool getInstance() {
        return INSTANCE;
    }

    /*---------------------------- 方法参数 ----------------------------*/
    /**
     * 执行懒加载数据库连接地址
     */
    private static String url = null;
    /**
     * 执行懒加载驱动名称
     */
    private static String driverClassName = null;
    /**
     * 执行懒加载用户名
     */
    private static String username = null;
    /**
     * 执行懒加载用户密码
     */
    private static String password = null;

    /**
     * 默认初始化连接池大小
     */
    private static Integer initialSize = 4;

    /**
     * 默认最大连接池大小为8
     */
    private static Integer maxActive = initialSize << 1;

    /**
     * 连接最大等待时间 单位：毫秒
     */
    private static Long maxWait = 10000L;

    /**
     * 当前拿到了数据库连接池的哪个值
     */
    private static Integer poolSize = 0;

    /**
     * 用来保存数据库连接
     */
    private static ConcurrentLinkedQueue<Connection> poolQueue = null;


    /**
     * 读取配置文件的对象
     */
    private static final Properties props = new Properties();

    /**
     * 文件路径地址
     */
    private static String userPropertiesPath = null;

    /*---------------------------- 静态代码块初始化 ---------------------------- */
    static {
        try {
            String resourcePath = getResourcePath();
            InputStream in = new FileInputStream(resourcePath);
            props.load(in);
            url = props.getProperty("url");
            driverClassName = props.getProperty("driverClassName");
            username = props.getProperty("username");
            password = props.getProperty("password");
            initialSize = props.getProperty("initialSize") == null ?
                    initialSize :
                    Integer.parseInt(props.getProperty("initialSize"));
            maxActive = props.getProperty("maxActive") == null ?
                    maxActive :
                    Integer.parseInt(props.getProperty("maxActive"));
            maxWait = props.getProperty("maxWait") == null ?
                    maxWait :
                    Long.parseLong(props.getProperty("maxWait"));
            poolQueue = new ConcurrentLinkedQueue<>();
            Class.forName(driverClassName);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /*---------------------------- 方法 ---------------------------- */

    /**
     * 获取配置文件路径
     *
     * @return 返回配置文件路径
     */
    private static String getResourcePath() {
        // 获取路径class编译路径
        // /E:/IdeaHome/SourceCode/kangaroo-orm/out/test/jdbc-template/
        // 此时应该删除前面的路径 /
        String pathDir = KangarooPool.class.getResource("/").getPath();
        String reallyDir = new StringBuffer(pathDir).deleteCharAt(0).toString();
        File targetPath = new File(reallyDir);
        getKangarooPoolPropertiesPath(targetPath);
        if (null != userPropertiesPath) {
            return userPropertiesPath;
        }
        throw new ResourceNotFoundException("无法找到或者加载 kangaroo-pool.properties 文件");
    }

    /**
     * 获取配置文件路径
     *
     * @param file 对象
     */
    private static void getKangarooPoolPropertiesPath(File file) {
        assert file != null;
        File[] files = file.listFiles();
        assert files != null;
        for (File f : files) {
            assert f != null;
            if (f.isDirectory()) {
                getKangarooPoolPropertiesPath(f.getAbsoluteFile());
            } else {
                if ("kangaroo-pool.properties".equalsIgnoreCase(f.getName())) {
                    userPropertiesPath = f.getAbsolutePath();
                    return;
                }
            }
        }
    }

    /**
     * 获取连接信息
     *
     * @return 返回数据库连接对象
     */
    public synchronized Connection getConnection() throws Exception {
        if (poolSize >= maxActive) {
            this.wait();
            // throw new NoConnectionException("连接池暂时没有可用的连接");
        } else {
            createConnection();
        }
        Connection remove = poolQueue.remove();
        if (poolSize > 1) {
            poolSize--;
        }
        if (null == remove) {
            createConnection();
            remove = poolQueue.remove();
        }
        return remove;
    }


    /**
     * 创建连接
     *
     * @return 返回数据库连接对象
     * @throws Exception
     */
    public synchronized void createConnection() throws Exception {
        // 每次调用，只要小于最大值，即创建对象
        if (poolSize <= maxActive) {
            Connection conn = DriverManager.getConnection(url, username, password);
            poolQueue.add(conn);
            poolSize++;
            System.out.println("创建了：" + conn);
            System.out.println("此时连接池大小：" + getPoolSize());
        } else {
            close();
        }
    }

    /**
     * 销毁连接池
     */
    public synchronized static void distory() throws SQLException {
        if (poolSize == 0) {
            return;
        }
        while (!poolQueue.isEmpty()) {
            poolQueue.remove().close();
        }
        poolSize = 0;
        System.out.println("连接池已经清空");
    }

    /**
     * 关闭数据库连接
     *
     * @param conn 需要关闭的连接
     */
    public synchronized void close(Connection conn) throws Exception {
        // 如果数据库连接为 null 直接结束方法
        if (null == conn) {
            return;
        }
        poolSize++;
        poolQueue.add(conn);
        close();
    }

    /**
     * 获取数据库连接池的连接数量
     *
     * @return 返回数据库连接池的连接数量
     */
    public Integer getPoolSize() {
        return poolSize;
    }

    /**
     * 关闭连接
     *
     * @throws Exception
     */
    private synchronized void close() throws Exception {
        // 数据连接大于 初始值，小于最大值 是可以销毁的连接
        // 等待 maxWait 的时间
        TimeUnit.MILLISECONDS.sleep(maxWait);
        if (poolSize >= initialSize) {
            poolSize--;
        }
        this.notifyAll();
    }
}
